import { Rechange } from 'rechange-model.js';
var ch = new Rechange();
Page({
  data: {
    radioItems: [
      { name: '微信支付', img: '../../imgs/wechat.png',value: '0','checked':true }
      // { name: '银联支付', img: '../../imgs/pay.png', value: '1', checked: true }
    ],
    btnType:'disable',
    onLoading:false,
  },
  onLoad: function (options) {
    //如果从订单入口进来，获取订单参数，以便设置完成后跳转回去
    this.data.type = options.type ? options.type : '';
    this.data.id = options.id ? options.id : '';
  },
  rechange:function(){
    var that = this ;
    if (!this.data.money || this.data.money <=0){
      wx.showToast({
        title: '请先填写充值金额',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    //如果正在充值不操作，避免用户错误的频繁点击按钮
    if (that.data.onLoading){
      return false;
    }
    that.data.onLoading = true;
    var args = { 
      'money': this.data.money
    }
    ch.rechange(args,(data) => {
      that.data.onLoading = false;
      if (data == 2) {
        if (that.data.type == 1) {
          var url = "../order/payment?order_id=" + that.data.id;
        } else if (that.data.type == 2) {
          var url = "../order/payment?parent_sn=" + that.data.id;
        } else {
          var url = '../center/wallet'
        }
        wx.showToast({
          title: '充值成功',
          icon: 'success',
          duration: 2000,
          success: function () {
            setTimeout(function () {
              wx.navigateTo({
                url: url
              });
            }, 2000)
          }
        })
      } else if (data == 0 || data == 1) {
        wx.showToast({
          title: '充值失败',
          icon: 'none',
          duration: 2000,
        })
      }else{
        wx.showToast({
          title: '调用微信支付时发生错误',
          icon: 'none',
          duration: 2000,
          success: function () {
            setTimeout(function () {
              wx.navigateTo({
                url: '../center/wallet'
              });
            }, 2000)
          }
        })
      }
    });
  },

  //支付方式
  radioChange: function (e) {
    var radioItems = this.data.radioItems;
    for (var i = 0, len = radioItems.length; i < len; ++i) {
      radioItems[i].checked = radioItems[i].value == e.detail.value;
    }

    this.setData({
      radioItems: radioItems
    });
  },
  //获取充值金额，并判断充值按钮样式
  moneyChange: function (e) {
    var val = e.detail.value;
    if (val.indexOf(".") != -1 && val.substring(val.indexOf("."), val.length).length > 2){
      val = parseFloat(val).toFixed(2);
    }
    let type = 'disable';
    if(val && val > 0){
      type = 'btn'
    }
    this.setData({
      btnType: type,
      money : val
    })
  },
})